// pages/apps/user/address4Shipping/address4Shipping.ts
Page({
  /**
   * 页面的初始数据
   */
  data: {
    shippingAddrList: [{ isCurr: false }],
    ui_add: ""
  },
  onLoad() {
    try {
      var shippingAddrListObj = wx.getStorageSync('shippingAddrList')
      if (shippingAddrListObj != null && shippingAddrListObj != "") {
        this.setData({ shippingAddrList: shippingAddrListObj })
      }
    } catch (e) { }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onShow() {
    this.getListForCurrUser();
  },
  goAddOrEdit(param: any) {
    const bean = param.currentTarget.dataset.bean
    wx.navigateTo({
      url: '/pages/apps/user/address/address4ShippingEdit/address4ShippingEdit',
      events: {
      },
      success: function (res) {
        res.eventChannel.emit('pageData', { bean: bean })
      }
    })
  },
  /**
   * 获得收货地址列表
   */
  getListForCurrUser() {
    var that = this
    const token = wx.getStorageSync('token')
    const preUrl = getApp().globalData.SERVER_URL
    const url = preUrl + "fc/emall/shippingAddress/listForCurrUser"
    // console.error("url: " + url)
    wx.request({
      url: url,
      method: 'GET',
      data: {
        pageNo: 1,
        pageSize: 100
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded', // 默认值
        'X-Access-Token': token,
        'Tenant-Id': '-1'
      },
      success(res: any) {
        // console.error("结果: " + JSON.stringify(res))
        wx.stopPullDownRefresh()
        if (res.data.code == 200) {
          const list = res.data.result.records;
          if (list != null && list.length > 0) {
            try {
              var shoppingAddressJSON = wx.getStorageSync('address_4_curr_shopping')
              if (shoppingAddressJSON != null) {
                const shoppingAddress = JSON.parse(shoppingAddressJSON)
                for (let index = 0; index < list.length; index++) {
                  const address = list[index];
                  if (address.id == shoppingAddress.id) {
                    address.isCurr = true
                  } else {
                    address.isCurr = false
                  }
                }
              }
            } catch (e) {
              console.error("e = ", JSON.stringify(e))
            }
          }
          // console.error("list = ", JSON.stringify(list))
          that.setData({ shippingAddrList: list })
          try {
            wx.setStorageSync('shippingAddrList', list)
          } catch (e) { }
        } else {
          console.info(JSON.stringify(res))
        }
      },
      complete(_) {
        wx.setNavigationBarTitle({ title: "我的地址" })
        that.setData({ui_add:"新增地址"})
      }
    })
  },
  doSelectedItem(param: any) {
    const bean = param.currentTarget.dataset.bean
    try {
      wx.setStorage({
        key: 'address_4_curr_shopping',
        data: JSON.stringify(bean)
      })
    } catch (e) {
      console.error("e = ", JSON.stringify(e))
    }
    wx.navigateBack({})
  },
})